package lch.controller;

import lch.constant.MessageConstant;
import lch.constant.RedisMessageConstant;
import lch.entity.Result;
import lch.utils.SMSUtils;
import lch.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * @author lch
 * @date 2019-12-24 11:29
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/send40rder")
    public Result send40rder(String telephone) {
        //随机生成4位的验证码
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        try {
            //发送短信至用户,第一个是模板，第二个参数是手机号，第三个是验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        //存储验证码300秒，之后会进行验证，时间到了就失效了
        jedisPool.getResource().setex(telephone + RedisMessageConstant.SENDTYPE_ORDER, 300,code.toString());
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    @RequestMapping("/send4Login")
    public Result send4Login(String telephone) {
        //随机生成4位的验证码
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        try {
            //发送短信至用户,第一个是模板，第二个参数是手机号，第三个是验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        //存储验证码300秒，之后会进行验证，时间到了就失效了
        jedisPool.getResource().setex(telephone + RedisMessageConstant.SENDTYPE_LOGIN, 300,code.toString());
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
